package com.ungao.framework.proxy;


import com.ungao.framework.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

public class MapperProxy implements InvocationHandler {

    private SqlSession sqlSession;

    public MapperProxy(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //不做任何处理，直接放行
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }

        //组装mapper缓存key-> namespace.id
        String statementKey = method.getDeclaringClass().getName() + "." + method.getName();
        if (Collection.class.isAssignableFrom(method.getReturnType())) {
            return sqlSession.selectList(statementKey, args);
        } else if (Map.class.isAssignableFrom(method.getReturnType())) {
            return null;
        } else {
            return sqlSession.selectOne(statementKey, args);
        }
    }
}
